import { BaseCommand, TSelectRanage, TMergeCell } from '../types/common.interface';
import { TableDatas } from '../cors/table-datas';
import { Config } from '../cors/config';
import { RenderTrigger } from '../cors/render-trigger';
import { objTransformToClass, classTransformToObj } from '../decorators/toJSON';
import { Row } from '../cors/row';
import { Cell } from '../cors/cell';
import { MergeCell } from '../cors/merge-cell';
import { Select } from '../cors/select';

export class DeleteColCommand extends BaseCommand {
    protected past: {row: number; cells: any[]}[] = [];
    protected pastConf: any = {};
    protected pastMergeCells: any = {};
    protected pastSelect: any = null;
    constructor(
        protected tableDatas: TableDatas,
        protected renderTrigger: RenderTrigger,
        protected conf: Config,
        protected mergeCell: MergeCell,
        protected select: Select,
        protected cols: number[]
    ) {
        super();
    }
    public execute(): boolean {
        this.pastConf = classTransformToObj(this.conf);
        this.pastSelect = classTransformToObj(this.select);
        this.pastMergeCells = classTransformToObj(this.mergeCell);
        this.past = this.tableDatas.deleteCols(this.cols);
        this.renderTrigger.triggerRenderAll();
        return true;
    }
    protected addCells() {
        for(let item of this.past) {
            if(!this.tableDatas.rows[item.row]) {
                this.tableDatas.rows[item.row] = this.tableDatas.factory(Row); 
            }
            for(let cell of item.cells) {
                let cellInstance = this.tableDatas.factory(Cell);
                objTransformToClass(cellInstance, cell);
                if(cell.col >= this.tableDatas.rows[item.row].cells.length) {
                    this.tableDatas.rows[item.row].cells[cell.col] = cellInstance;
                } else {
                    this.tableDatas.rows[item.row].cells.splice(cell.col, 0, cellInstance);
                }
            }
        }
    }
    public redo(): boolean {
        objTransformToClass(this.conf, this.pastConf);
        objTransformToClass(this.select, this.pastSelect);
        objTransformToClass(this.mergeCell, this.pastMergeCells);
        this.addCells()
        this.renderTrigger.triggerRenderAll();
        return true;
    }
}